package com.clstu.homework;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Homework03Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getByName("192.168.1.5"), 9999);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你想要下载的歌曲名字");
        String musicName = scanner.next();
        bw.write(musicName);
        bw.newLine();//结束标记
        bw.flush();//送入数据通道

        //接受歌曲并且存入本地
        InputStream inputStream = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String ack = br.readLine();
        String path = "D:\\CloudMusic\\" + musicName + "的下载.mp3";
        if(!ack.equals("找到了")) {
            path = "D:\\CloudMusic\\" + "mkbk.jpg";
            System.out.println("你要找到音乐不存在,给你看个玛卡巴卡~~~~");
        }
        FileOutputStream fileOutputStream = new FileOutputStream(path);
        int readLen = 0;
        byte[] buf = new byte[1024];
        while ((readLen = inputStream.read(buf))!=-1){//保存文件
            fileOutputStream.write(buf,0,readLen);
        }
        System.out.println("音乐已经下载到了您的本地..");
        inputStream.close();//关闭资源
        fileOutputStream.close();
        socket.close();
        bw.close();
    }
}
